//
//  RTDatePicker.m
//  CustomTabBar
//
//  Created by 张志恒 on 16/4/15.
//  Copyright © 2016年 张志恒. All rights reserved.
//

#import "RTDatePicker.h"

@interface RTDatePicker ()

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) UIControl *overlayView;
@property (nonatomic, assign, getter = isShowing) BOOL showing;

@end

@implementation RTDatePicker

- (instancetype)init
{
    return [self initWithFrame:CGRectZero];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

#pragma mark - private methods
- (void)commonInit {
    self.backgroundColor = [UIColor colorWithRed:230/255.f
                                           green:230/255.f
                                            blue:230/255.f
                                           alpha:1];
    self.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, 258);
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setFrame:CGRectMake(20, 0, 42, 38)];
    [cancel setTitleColor:[UIColor colorWithRed:25/255.f green:133/255.f blue:218/255.f alpha:1] forState:UIControlStateNormal];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel.titleLabel setFont:[UIFont boldSystemFontOfSize:19]];
    [cancel addTarget:self action:@selector(cancelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancel];
    
    
    UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirm setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-38-20, 0, 42, 38)];
    [confirm setTitleColor:[UIColor colorWithRed:25/255.f green:133/255.f blue:218/255.f alpha:1] forState:UIControlStateNormal];
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm.titleLabel setFont:[UIFont boldSystemFontOfSize:19]];
    [confirm addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:confirm];
    
    [self addSubview:self.datePicker];
}

#pragma mark - public methods
- (void)show {
    if (self.isShowing) {
        return;
    }
    
    self.datePicker.date = self.defaultDate ?: [NSDate date];
    
    if (!self.overlayView.superview) {
        NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
        for (UIWindow *window in frontToBackWindows) {
            BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
            BOOL windowIsVisible = !window.hidden && window.alpha > 0;
            BOOL windowLevelNormal = window.windowLevel == UIWindowLevelNormal;
            
            if(windowOnMainScreen && windowIsVisible && windowLevelNormal) {
                [window addSubview:self.overlayView];
                break;
            }
        }
        
        [self.overlayView.superview bringSubviewToFront:self.overlayView];
    }
    
    if (!self.superview) {
        [self.overlayView addSubview:self];
    }
    
    [UIView animateWithDuration:0.25
                     animations:^{
                         self.overlayView.alpha = 1.f;
                         self.frame = CGRectMake(0, self.overlayView.frame.size.height - self.frame.size.height, self.overlayView.frame.size.width, self.frame.size.height);
                     } completion:^(BOOL finished) {
                         self.showing = YES;
                     }];
}

- (void)cancel {
    if (self.isShowing) {
        [UIView animateWithDuration:0.25
                         animations:^{
                             self.frame = CGRectMake(0, self.frame.origin.y + self.frame.size.height, self.frame.size.width, self.frame.size.height);
                             self.overlayView.alpha = 0.f;
                         }
                         completion:^(BOOL finished){
                             [self.overlayView removeFromSuperview];
                             self.overlayView = nil;
                             self.showing = NO;
                         }];
    }
}

#pragma mark - event responses
- (void)confirmBtnClick:(id)sender {
    [self cancel];
    if ([self.delegate respondsToSelector:@selector(datePickerDidClickConfirmButton:)]) {
        [self.delegate datePickerDidClickConfirmButton:self];
    }
}

- (void)cancelBtnClick:(id)sender {
    [self cancel];
    if ([self.delegate respondsToSelector:@selector(datePickerDidClickCancelButton:)]) {
        [self.delegate datePickerDidClickCancelButton:self];
    }
}

- (void)handleControlClicked:(id)sender {
    [self cancel];
}

#pragma mark - setters and getters
- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 42, [UIScreen mainScreen].bounds.size.width, 216)];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.backgroundColor = [UIColor whiteColor];
    }
    
    return _datePicker;
}

- (UIControl *)overlayView {
    if (!_overlayView) {
        _overlayView = [[UIControl alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _overlayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        _overlayView.alpha = 0.f;
        [_overlayView addTarget:self action:@selector(handleControlClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _overlayView;
}

- (NSDate *)date {
    return _datePicker.date;
}

- (NSString *)dateStr {
    return [self.formatter stringFromDate:_datePicker.date];
}

- (NSDateFormatter *)formatter {
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}

@end
